/*eslint-disable*/
import { ElMessage } from "element-plus";
import mainApi from "@/api/mainApi.js";
import courtIdDictionary from "../json/dictionary/courtIdDictionary";

const path = window.myApi.path
const fs = window.myApi.fs

export default {
    // 文件上传总起
    uploadFileRun(fileList, describeList, type) {
        // 读取文件仓库路径
        mainApi.readJson(ElMessage, (data) => {
            // 目标文件仓库
            let fileHouse = path.join(data.fileHouse, type)
            // 文件类型区分
            if (type === "court") {
                // 地板
                let modNameList = courtIdDictionary.
                    filter(item => item.value === describeList[0].data)
                    .map(obj => obj.id);
                // 获取各级文件夹路径
                let pathList = this.confirmFinalNameAndPath(describeList, fileHouse, modNameList)
                // 转存目标文件路径列表
                let targetPathList = [
                    {
                        name: "_fxxx.iff",
                        filePath: pathList.modPathList[0]
                    },
                    {
                        name: "预览图.jpg",
                        filePath: path.join(pathList.previewFolderPath, "preview.jpg")
                    }
                ]
                // 转存各级Mod文件
                this.modFileStore(pathList, fileList, targetPathList)
            }
            else if (type === "jersey") {
                // 球衣
                // 获取各级文件夹路径
                let pathList = this.confirmFinalNameAndPath_Jersey(describeList, fileHouse, fileList)
                // 转存目标文件路径列表
                let targetPathList = []
                for (let index = 0; index < fileList.length; index++) {
                    const file = fileList[index];
                    targetPathList.push({
                        name: file.name,
                        filePath: pathList.modPathList[index]
                    })
                }
                // console.log(targetPathList);
                // 转存各级Mod文件
                this.modFileStore(pathList, fileList, targetPathList)
            }
            else if (type === "face") {
                // 面补
                let modNameList = [describeList[0].data.split("|")[0]]
                // 获取各级文件夹路径
                let pathList = this.confirmFinalNameAndPath_Face(describeList, fileHouse, modNameList)
                // 转存目标文件路径列表
                let targetPathList = [
                    {
                        name: "_png.iff",
                        filePath: path.join(pathList.faceFolderPath, `png${modNameList[0]}.iff`)
                    },
                    {
                        name: "_face.iff",
                        filePath: path.join(pathList.faceFolderPath, `face${modNameList[0]}.iff`)
                    },
                    {
                        name: "预览图.jpg",
                        filePath: path.join(pathList.previewFolderPath, "preview.jpg")
                    }
                ]
                // 转存各级Mod文件
                this.modFileStore(pathList, fileList, targetPathList)
            }
            else if (type === "blacktop") {
                describeList.unshift({})
                // 获取各级文件夹路径
                let pathList = this.confirmFinalNameAndPath(describeList, fileHouse, ["s616"])
                // 转存目标文件路径列表
                let targetPathList = [{
                    name: "s616.iff", filePath: pathList.modPathList[0]
                },
                {
                    name: "预览图.jpg", filePath: path.join(pathList.previewFolderPath, "preview.jpg")
                }]
                // 转存各级Mod文件
                this.modFileStore(pathList, fileList, targetPathList)
            }
            else if (type === "scoreboard") {
                describeList.unshift({})
                // 获取各级文件夹路径
                let pathList = this.confirmFinalNameAndPath(describeList, fileHouse, ["newscorebug"])

                // 转存目标文件路径列表
                let targetPathList = [{
                    name: "newscorebug.iff", filePath: pathList.modPathList[0]
                },
                {
                    name: "预览图.jpg", filePath: path.join(pathList.previewFolderPath, "preview.jpg")
                }]
                // 转存各级Mod文件
                this.modFileStore(pathList, fileList, targetPathList)
            }
        });
    },
    // 确认最终文件名及路径
    confirmFinalNameAndPath(describeList, fileHouse, modNameList) {
        // 新文件夹名称
        let mainFolderName = `0 ${describeList[1].data + Math.floor(Date.now() / 1000)} ${describeList[2].data}`
        // console.log(mainFolderName);
        // 主文件夹路径
        let mainFolderPath = path.join(fileHouse, mainFolderName)

        // mod文件目标路径
        let modPathList = []
        modNameList.forEach(name => {
            modPathList.push(path.join(mainFolderPath, `${name}.iff`))
        });

        // 预览图文件夹
        let previewFolderPath = path.join(mainFolderPath, 'preview')

        // 返回文件及文件夹路径列表
        let pathList = {
            modPathList,
            newFolderList: [
                mainFolderPath,
                previewFolderPath
            ],
            mainFolderPath,
            previewFolderPath
        }
        return pathList
    },

    // 确认最终文件名及路径-面补
    confirmFinalNameAndPath_Face(describeList, fileHouse, modNameList) {
        // console.log(arguments);
        let pathList
        // 面补编号
        let faceId = modNameList[0]
        // 检查是否为新建球员
        let isNewPlayer = true
        // 执行检查
        try {
            const currentPlayerList = fs.readdirSync(fileHouse);
            currentPlayerList.forEach(element => {
                if (element === faceId) isNewPlayer = false
            });
        } catch (err) {
            ElMessage({ message: `遍历${fileHouse}文件夹失败：${err}`, type: "error" });
            mainApi.writeDailyLog(`遍历${fileHouse}文件夹失败：${err}` + "--upLoadApi.js")
        }
        // 面补集文件夹
        let faceListFolderPath = path.join(fileHouse, faceId)
        // 是新建球员
        if (isNewPlayer) {
            // 新建次序为1的面补文件夹
            let faceFolderPath = path.join(faceListFolderPath, `${faceId}-1 ${describeList[1].data} ${describeList[2].data}`)
            // 预览文件夹
            let previewFolderPath = path.join(faceFolderPath, "preview")
            pathList = {
                newFolderList: [
                    faceListFolderPath,
                    faceFolderPath,
                    previewFolderPath
                ],
                faceFolderPath,
                previewFolderPath
            }
        }
        // 不是新建球员
        else {
            // 依照现有次序+1新建面补文件夹
            try {
                // 次序+1
                let newFaceIndex = 0
                let fileIndexList = []
                fs.readdirSync(faceListFolderPath).forEach(element => {
                    fileIndexList.push(Number(element.split(" ")[0].split("-")[1]));
                });
                newFaceIndex = Math.max(...fileIndexList) + 1
                let faceFolderPath =
                    path.join(faceListFolderPath, `${faceId}-${newFaceIndex} ${describeList[1].data} ${describeList[2].data}`)
                // 预览文件夹
                let previewFolderPath = path.join(faceFolderPath, "preview")
                pathList = {
                    newFolderList: [
                        faceFolderPath,
                        previewFolderPath
                    ],
                    faceFolderPath,
                    previewFolderPath
                }
            } catch (err) {
                ElMessage({ message: `遍历${faceListFolderPath}文件夹失败：${err}`, type: "error" });
                mainApi.writeDailyLog(`遍历${faceListFolderPath}文件夹失败：${err}` + "--upLoadApi.js")
            }
        }
        return pathList
    },

    // 确认最终文件路径-球衣
    confirmFinalNameAndPath_Jersey(describeList, fileHouse, modList) {
        // 新文件夹名称
        let mainFolderName = `0 ${describeList[1].data}$${Math.floor(Date.now() / 1000)} ${describeList[2].data}`

        // 主文件夹路径
        let mainFolderPath = path.join(fileHouse, mainFolderName)

        // clothing文件夹路径
        let clothingFolderPath = path.join(mainFolderPath, 'clothing')

        // 预览图文件夹
        let previewFolderPath = path.join(mainFolderPath, 'preview')

        // mod文件目标路径
        let modPathList = []
        for (let index = 0; index < modList.length; index++) {
            // 文件名
            const modName = modList[index].filePath.split('\\')[modList[index].filePath.split('\\').length - 1];

            // waigua部分
            if (index < 2) {
                modPathList.push(path.join(clothingFolderPath, modName))
            }
            // clothing部分
            else if (index > 1 && index < 4) {
                modPathList.push(path.join(mainFolderPath, modName))
            }
            // preview部分
            else {
                modPathList.push(path.join(previewFolderPath, modName))
            }
        }

        console.log(modPathList);

        // 返回文件及文件夹路径列表
        let pathList = {
            modPathList,
            newFolderList: [
                mainFolderPath,
                clothingFolderPath,
                previewFolderPath
            ],
            mainFolderPath,
            previewFolderPath
        }
        return pathList
    },

    // 各级文件转存
    modFileStore(pathList, fileList, targetPathList) {
        console.log(pathList, fileList);
        // 新建文件夹路径列表
        let folderCreateList = []
        let folderCreateString = []
        let index = 0
        pathList.newFolderList.forEach(folder => {
            folderCreateList.push(fs.mkdirSync(folder))
            folderCreateString += `${index}.${folder}\n`
            index++
        });
        // 文件夹创建
        Promise.all(folderCreateList)
            .then(res => {
                // 日志记录
                mainApi.writeDailyLog(`新建文件夹成功\n${folderCreateString}` + "--upLoadApi.js");
                // 转存原始文件路径列表
                // let sourcePathList = [fileList[0], fileList[1]]
                let sourcePathList = fileList
                // 统一执行文件转存
                this.fileStoreRun(sourcePathList, targetPathList);
            })
            .catch(err => {
                console.log(err);
                ElMessage({ message: `新建文件夹失败：${err}` })
                mainApi.writeDailyLog(`新建文件夹失败：${err}` + "--upLoadApi.js");
            })
    },
    // 统一执行文件转存
    fileStoreRun(sourcePathList, targetPathList) {
        console.log(sourcePathList, targetPathList);
        sourcePathList.forEach(source => {
            if (source.filePath === "") return
            targetPathList.forEach(target => {
                if (target.name === source.name) {
                    // 源文件路径
                    const sourcePath = source.filePath
                    // 目标文件路径
                    const destinationPath = target.filePath

                    try {
                        fs.copyFileSync(sourcePath, destinationPath);
                        ElMessage({ message: `${source.name}转存成功` });
                    } catch (err) {
                        // 转存失败
                        ElMessage({ message: `${source.name}转存失败:${err}` });
                        mainApi.writeDailyLog(`${source.name}转存失败:${err}\n源路径:${sourcePath}\n目标路径:${destinationPath}` + "--upLoadApi.js");
                        // 删除文件夹
                        fs.rm(path.dirname(destinationPath), { recursive: true }, (err) => {
                            if (deletePathErr) {
                                mainApi.writeDailyLog(`删除${path.dirname(destinationPath)}文件夹失败:${deletePathErr}` + "--upLoadApi.js");
                            }
                            mainApi.writeDailyLog(`删除${path.dirname(destinationPath)}文件夹成功` + "--upLoadApi.js");
                        });
                    }
                }
            });
        });
    },
    // 整合文件夹文件识别
    folderFileIdentify(fileList, dataList, matchType, callback) {
        // 结果
        let resultList = []
        // 匹配
        if (!matchType) {
            // 单文件mod类型
            Object.values(fileList).forEach(file => {
                // 文件类型区分
                if (file.name.split(".")[1] === "iff") {
                    // console.log(`非图片：${file.name}`);
                    // 非图片
                    resultList.push({
                        name: dataList[0].name,
                        filePath: file.path
                    })
                }
                else {
                    // console.log(`图片：${file.name}`);
                    // 图片
                    resultList.push({
                        name: dataList[1].name,
                        filePath: file.path
                    })
                }
            });
        }
        // 面补匹配
        else if (matchType === "face") {
            // 字符标识列表
            let flagList = []
            let arr = [dataList[0], dataList[1]]
            arr.forEach(data => {
                flagList.push(data.name.split("_")[1].split(".")[0])
            })
            // 分类
            Object.values(fileList).forEach(file => {
                // 文件类型区分
                if (file.name.split(".")[1] === "iff") {
                    // 非图片
                    flagList.forEach(flag => {
                        if (file.name.indexOf(flag) != -1) {
                            // 文件名录入
                            resultList.push({
                                name: `_${flag}.iff`,
                                filePath: file.path
                            })
                        }
                    });
                }
                else {
                    // 图片
                    resultList.push({
                        name: dataList[2].name,
                        filePath: file.path
                    })
                }
            });
        }
        // 球衣匹配
        else if (matchType === "jersey") {
            // iff部分处理
            let iffList = [dataList[0], dataList[1], dataList[2], dataList[3]]
            // 字符标识列表
            let flagList = []
            iffList.forEach(data => {
                flagList.push(data.name.split("_")[1].split(".")[0])
            })
            console.log(flagList);
            // 分类
            Object.values(fileList).forEach(file => {
                // 文件类型区分
                if (file.name.split(".")[1] === "iff") {
                    // 非图片
                    flagList.forEach(flag => {
                        if (file.name.indexOf(flag) != -1) {
                            // _current.iff特殊处理
                            if (flag === "current" && file.name.indexOf("clothing_resource") != -1) return
                            // 文件名录入
                            resultList.push({
                                name: `_${flag}.iff`,
                                filePath: file.path
                            })
                        }
                    });
                }
                else {
                    // 图片
                    resultList.push({
                        name: dataList[4].name,
                        filePath: file.path
                    })
                }
            });
        }

        // 返回
        callback(resultList);
    }
}